package scatter.identifier.rest.controller;

import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.http.HttpStatus;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseStatus;
import org.springframework.web.bind.annotation.RestController;
import scatter.common.LoginUser;
import scatter.common.rest.controller.SuperController;
import scatter.common.rest.exception.UserNotLoginException;
import scatter.identifier.rest.IdentifierConfiguration;
import springfox.documentation.annotations.ApiIgnore;

/**
 * Created by yangwei
 * Created at 2020/12/11 14:20
 */
@Api(tags = "用户登录标识相关接口")
@RestController
@RequestMapping(IdentifierConfiguration.CONTROLLER_BASE_PATH + "/identifier/login")
public class IdentifierLoginController extends SuperController {

    @ApiOperation("判断用户是否登录")
    @GetMapping("/hasLogin")
    @ResponseStatus(HttpStatus.OK)
    public Boolean hasLogin() {
        boolean b = SecurityContextHolder.getContext().getAuthentication() != null &&
                SecurityContextHolder.getContext().getAuthentication().isAuthenticated() &&
                //when Anonymous Authentication is enabled
                !(SecurityContextHolder.getContext().getAuthentication()
                        instanceof AnonymousAuthenticationToken);
        if (!b) {
            throw new UserNotLoginException("用户未登录");
        }
        return b;
    }

    @PreAuthorize("hasAuthority('user')")
    @ApiOperation("获取当前登录用户信息")
    @GetMapping("/userinfo")
    @ResponseStatus(HttpStatus.OK)
    public LoginUser info(@ApiIgnore LoginUser loginUser) {
        return loginUser;
    }
}
